//
//  UIView+YH.m
//  MoreCoin
//
//  Created by 林宁宁 on 2019/9/23.
//  Copyright © 2019 MoreCoin. All rights reserved.
//

#import "UIView+YH.h"
#import <objc/runtime.h>
#import "UIColor+YHStyle.h"
#import "UIView+YHFrame.h"

@implementation UIView (YH)

/** 顶部圆角*/
- (void)cornerTop:(float)corner{
    [self corner:corner pos:UIRectCornerTopLeft | UIRectCornerTopRight];
}
/** 左部圆角*/
- (void)cornerLeft:(float)corner
{
    [self corner:corner pos:UIRectCornerTopLeft | UIRectCornerBottomLeft];
}
/** 底部圆角*/
- (void)cornerBottom:(float)corner{
    [self corner:corner pos:UIRectCornerBottomLeft | UIRectCornerBottomRight];
}
/** 右部圆角*/
- (void)cornerRight:(float)corner
{
    [self corner:corner pos:UIRectCornerTopRight | UIRectCornerBottomRight];
}

- (void)cornerAll:(float)corner{
    [self corner:corner pos:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight];
}
- (void)cornerAllGarden{
    if(CGRectIsEmpty(self.bounds)){
        [self layoutIfNeeded];
    }
    [self cornerAll:MIN(self.yh_width,self.yh_height)*0.5];
}

- (void)corner:(float)corner pos:(UIRectCorner)corners{
    if(CGRectIsEmpty(self.bounds)){
        [self layoutIfNeeded];
    }
    if (CGRectIsEmpty(self.bounds)) {
        self.layer.cornerRadius = corner;
        [self.layer setMasksToBounds:YES];
        return;
    }
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(corner, corner)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)cornerAllGardenColor:(UIColor *)color{
    [self cornerAllGardenWidth:1 withColor:color];
}

- (void)cornerAllGardenWidth:(CGFloat)width withColor:(UIColor *)color{
    if (CGRectIsEmpty(self.bounds)) {
        [self layoutIfNeeded];
    }
    [self cornerAll:MIN(self.yh_width, self.yh_height)*0.5 withWidth:width withColor:color];
}


- (void)cornerAll:(float)corner withWidth:(CGFloat)width withColor:(UIColor*)color{

   
    self.layer.cornerRadius = corner;
    [self.layer setMasksToBounds:YES];
    self.layer.borderWidth = width;
    self.layer.borderColor = color.CGColor;
}

- (void)cornerNone{
    if(!self.layer.mask){
        return;
    }
    self.layer.mask = nil;
}




/** uiview转成图片*/
- (UIImage *)yh_drawToImage{

    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。
    //如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;

}

/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向， NO 为垂直方向
 *
 */
- (void)yh_drawDottedLineWithLineLength:(double)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    
    [shapeLayer setBounds:self.bounds];
    
    if (isHorizonal) {
        
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame))];
        
    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame)/2)];
    }
    
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(self.frame)];
    } else {
        
        [shapeLayer setLineWidth:CGRectGetWidth(self.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(self.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(self.frame));
    }
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [self.layer addSublayer:shapeLayer];
}

- (void)yh_drawLineWithLineLength:(UIRectEdge)rectEdg{
    [self yh_drawLineWithLineLength:rectEdg lineLength:1 lineColor:[UIColor yh_separator]];
}
- (void)yh_drawLineWithLineLength:(UIRectEdge)rectEdg lineLength:(double)lineLength lineColor:(UIColor *)lineColor{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (CGRectIsEmpty(self.bounds)) {
            [self updateConstraintsIfNeeded];
        }
        void(^AddLineWithFrame)(CGRect lineFrame) = ^(CGRect lineFrame) {
            CALayer *lineLayer = [CALayer layer];
            lineLayer.frame = lineFrame;
            lineLayer.backgroundColor = lineColor.CGColor;
            //  把绘制好的虚线添加上来
            [self.layer addSublayer:lineLayer];
        };
        
        CGRect lineFrame = CGRectMake(0, 0, self.bounds.size.width, lineLength);
        if(rectEdg & UIRectEdgeTop){
            lineFrame = CGRectMake(0, 0, self.bounds.size.width, lineLength);
            AddLineWithFrame(lineFrame);
        }
        if(rectEdg & UIRectEdgeLeft){
            lineFrame = CGRectMake(0, 0, lineLength, self.bounds.size.height);
            AddLineWithFrame(lineFrame);
        }
        if(rectEdg & UIRectEdgeBottom){
            lineFrame = CGRectMake(0, self.bounds.size.height-lineLength, self.bounds.size.width, lineLength);
            AddLineWithFrame(lineFrame);
        }
        if(rectEdg & UIRectEdgeRight){
            lineFrame = CGRectMake(self.bounds.size.width-lineLength, 0, lineLength, self.bounds.size.height);
            AddLineWithFrame(lineFrame);
        }
    });
}

/** 判断View是否显示在屏幕上*/
- (BOOL)yh_isDisplayedInScreen{
    
    if(!self.window){
        return NO;
    }
    
    if (self == nil) {
        return FALSE;
    }
    CGRect screenRect = [UIScreen mainScreen].bounds;
    
    // 转换view对应window的Rect
    CGRect rect = [self convertRect:self.bounds toView:nil];
    if (CGRectIsEmpty(rect) || CGRectIsNull(rect)) {
        return FALSE;
    }
    // 若view 隐藏
    if (self.hidden) {
        return FALSE;
    }
    // 若没有superview
    if (self.superview == nil) {
        return FALSE;
    }
    // 若size为CGrectZero
    if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
        return  FALSE;
    }
    // 获取 该view与window 交叉的 Rect
    CGRect intersectionRect = CGRectIntersection(rect, screenRect);
    if (CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)) {
        return FALSE;
    }
    return TRUE;
}

- (UIViewController *)yh_vc{
    UIResponder *next = [self nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next !=nil);
    return nil;
}
- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}



-(CGFloat)getViewBottom{
    if (CGRectIsNull(self.frame)) {
        [self updateConstraintsIfNeeded];
    }
    NSArray * views= [self.subviews sortedArrayUsingComparator:^NSComparisonResult(UIView *view1 , UIView * view2){
        NSComparisonResult result = [@(view1.bottom).stringValue compare:@(view2.bottom).stringValue options:NSNumericSearch];
        //降序 从小到大
        return result == NSOrderedDescending;
    }];
    UIView * bottomView = views.lastObject;
    return bottomView.bottom;
}

-(void)addTapClick:(void (^)(void))click{
    if (!click) {
        return;
    }
    self.userInteractionEnabled = YES;
    objc_setAssociatedObject(self, _cmd, click, OBJC_ASSOCIATION_COPY_NONATOMIC);
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTouched:)];
    [self addGestureRecognizer:tap];
}
 
-(void)actionTouched:(UITapGestureRecognizer *)tap{
    void (^block)(void) = objc_getAssociatedObject(self, @selector(addTapClick:));
    if (block) {
        block();
    }
}



@end


@implementation UIView(YHShadow)

-(CALayer *)yh_shadowLayer{
    return objc_getAssociatedObject(self, @selector(yh_shadowLayer));
}
-(void)setYh_shadowLayer:(CALayer *)yh_shadowLayer{
    objc_setAssociatedObject(self, @selector(yh_shadowLayer), yh_shadowLayer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


/** 添加阴影*/
- (void)yh_addShadow:(void (^_Nullable)(CALayer *))shadowConfig{
    if (CGRectIsEmpty(self.bounds)) {
       [self layoutIfNeeded];
    }
    
    [self yh_cleanShadow];
    
    self.clipsToBounds = NO;
    
    CALayer *subLayer = [CALayer layer];
    self.yh_shadowLayer = subLayer;
    CGRect fixframe = self.frame;
    subLayer.frame = fixframe;
    subLayer.cornerRadius = self.layer.cornerRadius;
    subLayer.backgroundColor = [[UIColor yh_background] colorWithAlphaComponent:0.3].CGColor;
    subLayer.masksToBounds = NO;
    subLayer.shadowColor = [[UIColor yh_background] colorWithAlphaComponent:0.3].CGColor;
    subLayer.shadowOffset = CGSizeMake(3,3);
    subLayer.shadowOpacity = 1;
    subLayer.shadowRadius = 5;//阴影半径，默认3
    if(shadowConfig){
        shadowConfig(subLayer);
    }
    [self.superview.layer insertSublayer:subLayer below:self.layer];
}

- (void)yh_renderShadow{
    [self yh_renderShadow:^(CALayer * _Nullable shadowLayer) {
        shadowLayer.shadowColor = [UIColor yh_shadow].CGColor;
        shadowLayer.shadowOffset = CGSizeZero;
        shadowLayer.shadowRadius = 10;
        shadowLayer.shadowOpacity = 0.4;
        shadowLayer.cornerRadius = 4;
    }];
}

- (void)yh_renderShadow:(void (^_Nullable)(CALayer *))shadowConfig{
    self.clipsToBounds = NO;
    if(shadowConfig){
        shadowConfig(self.layer);
    }
}

-(void)yh_cleanShadow{
    if(self.yh_shadowLayer != nil){
        [self.yh_shadowLayer removeFromSuperlayer];
        self.yh_shadowLayer = nil;
    }
}

@end



@implementation UIView(YHColor)

- (void)yh_gradientColors:(NSArray <UIColor *> *)colors locations:(NSArray<NSNumber *> * _Nullable)locations{
    NSMutableArray *colorArray = [NSMutableArray array];
    for(UIColor * color in colors){
        [colorArray addObject:(id)color.CGColor];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        CAGradientLayer * gradient = [CAGradientLayer layer];
        gradient.frame = self.bounds;
        gradient.startPoint = CGPointMake(0, 0);
        gradient.endPoint = CGPointMake(1, 0);
        if(locations){
            gradient.locations = locations;
        }
        gradient.colors = colorArray;
        [self.layer.sublayers enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj isKindOfClass:[CAGradientLayer class]]){
                [obj removeFromSuperlayer];
                *stop = YES;
            }
        }];
        [self.layer insertSublayer:gradient atIndex:0];
    });
}
- (UIColor *)yh_colorAtPoint:(CGPoint)point{
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    CGContextTranslateCTM(context, -point.x, -point.y);
    [self.layer renderInContext:context];
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    return color;
}



@end
